import axios from "axios"
import { Toast } from "antd-mobile"

let baseUrl = ""
let $pre = ""
// 判断环境
if (process.env.NODE_ENV === "development") {
    baseUrl = "/api"
    $pre = "http://localhost:1000"
}

export { $pre }

// 请求拦截
axios.interceptors.request.use(config => {
    // console.log(config);
    config.url = baseUrl + config.url;
    // console.log(config.url);

    // 如果访问的不是登陆和注册,给每个http的header上都加上token
    if (config.url !== baseUrl + "/api/login" && config.url !== baseUrl + "/api/register") {
        config.headers.authorization = JSON.parse(sessionStorage.getItem("userInfo")).token;
    }
   

    return config
})


// 响应拦截
axios.interceptors.response.use(res => {
    console.group("request url:" + res.config.url)
    console.log(res);
    console.groupEnd()

    // 处理失败
    if (res.data.code != 200) {
        Toast.show({ content: res.data.msg })
    }

     //掉线
     if (res.data.msg == "登录已过期或访问权限受限") {
        sessionStorage.removeItem("userInfo")
        window.open("/", "_self")
    }

    return res;
})




// get请求
export const get = (url, params = {}) => {
    return axios({
        url,
        method: "get",//可以省略不写
        params
    })
}


// post请求
export const post = (url, params = {}, haveFile = false) => {
    let d = null;
    if (haveFile) {
        d = new FormData()
        for (let key in params) {
            d.append(key, params[key])
        }
    } else {
        d = params
    }

    return axios({
        url,
        method: "post",
        data: d
    })
}